<?php

declare(strict_types=1);
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://hyperf.wiki
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf/hyperf/blob/master/LICENSE
 */

namespace App\Controller;

use App\Constants\ServerCode;
use App\Request\UserValidation;
use App\Service\ReturnMessageService;
use App\Service\UserService;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\GetMapping;
use Hyperf\HttpServer\Annotation\PostMapping;
use Hyperf\HttpServer\Contract\RequestInterface;
use Hyperf\Validation\Contract\ValidatorFactoryInterface;
use const OpenTracing\Tags\ERROR;

#[Controller(prefix: "/user")]
class UserController
{

    #[Inject]
protected ValidatorFactoryInterface $validationFactory;

    #[Inject]
    protected UserService $user_service;

    #[inject]
    protected ReturnMessageService $returnMessageService;

    #[Inject]
    protected UserValidation $user_validation;



//    public function index(RequestInterface $request, ResponseInterface $response)
//    {
//        return $response->raw('Hello Hyperf!');
//    }

    /**
     * Notes:注册用户
     * User: xsz
     * Date: 2024/5/15 17:23
     */
    #[PostMapping(path: "register")]
    public function register(RequestInterface $request){
        $request_data =$request->all();
        $validator = $this->validationFactory->make(
            $request_data,
            $this->user_validation->register(),
            $this->user_validation->messages()
        );

        if ($validator->fails()) {
            //
            $validator->errors();
            return $this->returnMessageService->buildReturnMessage(false,$validator->errors()->first(),ServerCode::ERROR_PARAMETERS);
        }


        $result = $this->user_service->register($request_data);

        return $this->returnMessageService->buildReturnMessage($result['status'],$result['message'],$result['code']);
    }


    /**
     * Notes:用户登录
     * User: xsz
     * Date: 2024/5/15 17:23
     */
    #[GetMapping(path: "login")]
    public function login(RequestInterface $request){
        $request_data =$request->all();
        $validator = $this->validationFactory->make(
            $request_data,
            $this->user_validation->register(),
            $this->user_validation->messages()
        );

        if ($validator->fails()) {
            //
            $validator->errors();
            return $this->returnMessageService->buildReturnMessage(false,$validator->errors()->first(),ServerCode::ERROR_PARAMETERS);
        }
        $result = $this->user_service->login($request_data);

        return $this->returnMessageService->buildReturnMessage($result['status'],$result['message'],$result['code']);
    }

}
